/*
 * @Author: Guiter 1336263157@qq.com
 * @Date: 2023-11-18 17:00:18
 * @LastEditors: Guiter 1336263157@qq.com
 * @LastEditTime: 2023-11-29 10:35:13
 * @FilePath: \nuxt3-music-player\src\server\api\login.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { http } from '~/server';
import type { Unikey, UnikeyData, Qrimg, CreateCode } from '~/types/login';

/* 二维码登录 */

/**
 * 获得二维码key
 * @returns 如果 code == 200 调用 createKey
 */
export async function getKey(): Promise<Unikey> {
  const { data } = await http.get<UnikeyData>('/login/qr/key');
  return data;
}

/**
 * 二维码生成接口
 * @param key string
 * @returns
 */
export async function createKey(key: string): Promise<Qrimg> {
  const { data } = await http.get<CreateCode>('/login/qr/create', {
    key,
    timestamp: new Date().getTime(),
    qrimg: true
  });
  return data;
}

/* 检测二维码状态 */
export async function checkKey(
  key: string
): Promise<{ code: number; message: string; cookie: string }> {
  return await http.get<{
    code: number;
    message: string;
    cookie: string;
  }>('/login/qr/check', {
    key,
    timestamp: new Date().getTime()
  });
}

/**
 * 退出登录
 */
export async function layout(): Promise<void> {
  const res = await http.get<{ code: number }>('/logout');
  if (res.code === 200) {
    useResetStore();
    useMessage({
      message: '退出成功',
      type: 'success'
    });
  }
}

/**
 * 刷新登录
 * @returns 返回新的cookie
 */
export async function refresh(): Promise<{ code: number; cookie: string }> {
  return await http.get<{ code: number; cookie: string }>('/login/refresh');
}
